import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //通过start方法来启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!!!");
        //服务器循环等待响应
        while(true){
            //1.接受请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            //2.处理请求
            String response = process(request);

            //3.将响应发送给客户端
            DatagramPacket responsePacket = new DatagramPacket(
                    response.getBytes(),
                    response.getBytes().length,
                    requestPacket.getSocketAddress()
            );
            System.out.println(requestPacket.getSocketAddress().toString());
            socket.send(responsePacket);

            System.out.printf("[client: %s, %d]: %s",
                    requestPacket.getAddress().toString(),
                    requestPacket.getPort(),
                    request);
        }
    }

    private String process(String response){
        return response;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
